<template>
  <!-- 移除原有layout结构 -->
  <div class="grid-container">

    <n-grid cols="1" rows="auto 1fr" :style="{ height: '100vh' }" >

      <n-gi>
        <n-grid cols="24" :x-gap="16" :style="{ height: '100%' }">


          <n-gi :span="false ? 20 : 24">
            <n-card class="main-content">
              <n-tabs
                type="line"
                animated
                v-model:value="activeTab"
                @update:value="handleTabChange"
                @click="handleTabClick"
                class="full-height-tabs"
               >

               <n-tab-pane 
                v-for="tab in tabs" 
                :key="tab.name"
                :name="tab.name"
                :title="tab.name"
                style="height: 100%;"
                >

                <template #tab>
                  <n-tooltip trigger="hover" placement="top">
                    <template #trigger>
                      <span class="tab-label">{{ tab.label }}</span>
                    </template>
                    {{ tab.tooltip }}
                  </n-tooltip>
                </template>


                <n-form
                  v-if="flushForm"
                  ref="twoExcelFormRef"
                  :label-width="80"
                  :model="twoExcelForm"
                  :rules="twoExcelRules"
                 >
                      <n-form-item label="第一个EXCEL" path="excelOneName">
                          <n-upload
                              ref="imgUploadRefOne" 
                              :max="1" :file-list="excelOne"
                              @remove="handleRemoveExcelOne" @change="handleFileOneChange"
                           >
                              <n-upload-dragger>
                                  <div class="upload-tips">
                                      <n-icon depth="1" size="30" color="#aa55ff">
                                        <DocumentAttach />
                                      </n-icon>
                                      <br/>
                                      <n-text depth="1" style="font-size: 14px;color:#aa55ff">
                                        点击或拖拽
                                        </n-text><br/>
                                      <n-p depth="1" style="margin: 0 0; font-size: 12px;color:#aa55ff">
                                          用以对比两个Excel中所有单元格的不同之处(左侧)
                                      </n-p>
                                  </div>
                              </n-upload-dragger>
                              
                              <template #file="{ file }">
                                  <n-image
                                      :src="file.url"
                                      :alt="file.name"
                                      width="300"
                                      height="300"
                                      object-fit="cover"
                                      preview-disabled
                                  >
                                      <template #placeholder>
                                      <n-spin size="large" />
                                      </template>
                                  </n-image>
                              </template>
                          </n-upload>
                      </n-form-item>
                      <n-form-item label="第二个EXCEL" path="excelTwoName">
                          <n-upload
                              ref="imgUploadRefTwo" 
                              :max="1" :file-list="excelTwo"
                              @remove="handleRemoveExcelTwo" @change="handleFileTwoChange"
                           >
                              <n-upload-dragger>
                                  <div class="upload-tips">
                                      <n-icon depth="1" size="30" color="#aa55ff">
                                        <DocumentAttach />
                                      </n-icon>
                                      <br/>
                                      <n-text depth="3" style="font-size: 14px;color:#aa55ff">
                                        点击或拖拽
                                      </n-text>
                                      <br/>
                                      <n-p depth="3" style="margin: 0 0; font-size: 12px;color:#aa55ff">
                                          请保证文件中种列数和结构相同（右侧）
                                      </n-p>
                                  </div>
                              </n-upload-dragger>
                              <template #file="{ file }">
                                  <n-image
                                      :src="file.url"
                                      :alt="file.name"
                                      width="300"
                                      height="300"
                                      object-fit="cover"
                                      preview-disabled
                                  >
                                      <template #placeholder>
                                      <n-spin size="large" />
                                      </template>
                                  </n-image>
                              </template>
                          </n-upload>
                      </n-form-item>
                      <n-button
                          size="medium"
                          color="#aa55ff"  
                          @click="chkExcelAllCellDiff"
                          :loading="isButtonShow"
                          :disabled="isButtonShow || !excelOne.length || !excelTwo.length"
                          >
                          <template #icon>
                              <n-icon size="20"> <CloudUpload /> </n-icon>
                          </template>
                          <span style="font-size: 16px; font-weight: bolder">
                              {{ isButtonShow ? '处理中...' : '开始对比' }}
                          </span>
                      </n-button>
                      <n-button
                          v-if="excelMinioUrl.length > 0"
                          style="margin-left: 10px"
                          size="medium" 
                          color="#aa55ff"
                          @click="openExternalUrl"
                          :loading="isButtonShow"
                          >
                          <template #icon>
                              <n-icon size="20"> <Download /> </n-icon>
                          </template>
                          <span style="font-size: 16px; font-weight: bolder">
                              {{ isButtonShow ? '生成中...' : '点击下载对比结果' }}
                          </span>
                      </n-button>
                  </n-form>

              </n-tab-pane>

              </n-tabs>
            </n-card>
          </n-gi>
        </n-grid>
      </n-gi>
    </n-grid>



  


  </div>
  
</template>

<script setup lang="ts">
// 在组件脚本顶部手动导入组件
// @ts-ignore
import { 
  useMessage,
  NTabs,
  NTabPane,
  FormInst,
  FormRules,
  UploadFileInfo
}  from 'naive-ui'
import { inject,ref,reactive,onMounted } from 'vue'
import { DocumentAttach,CloudUpload,Download,DocumentLock } from '@vicons/ionicons5'
import { VaeStore } from "../store";
import { storeToRefs } from "pinia";
const message=useMessage();
import request from '@/utils/request'
const store = VaeStore();
const { userInfo } = storeToRefs(store);
// 滚动条控制
const scrollBy = inject<Function>('scrollBy');
scrollBy?.(0)

const userdata = reactive({
  across_num: '',
  avatarBase64: '',
  avatar_url: '',
  create_tm: '',
  email: '',
  encrypt_pwd: '',
  encryption_algorithm: '',
  freeze_ornnt: '',
  id: '',
  role_num: '',
  tel_num: '',
  update_tm: '',
  username: '',
  wechat_abt: '',
})


// 选项卡配置数据
const tabs = ref([
  { 
    name: 'ChkExcelAllCell', 
    label: 'ChkExcelAllCell', 
    tooltip: '检查两个Excel所有单元格&生成结果Excel', 
    content: '处理TwoExcel'
  },
])
const tabOneIconSizeOne = ref(30); // 第一个TAB的图标大小
const tabOneIconSizeTwo = ref(30); // 第一个TAB的图标大小
const isButtonShow = ref(false); // 按钮是否显示加载状态
const textIsShowOne = ref(true); // 是否显示文字提示
const textIsShowTwo = ref(true); // 是否显示文字提示
const flushForm = ref(true); // 是否刷新表单
// 当前的 TAB 
const activeTab = ref('ChkExcelAllCell');
const handleTabChange = (value: string) => {};
// 当点击 TAB 的时候
const handleTabClick = (e: any) => {}

// 上传Excel进行处理 --------------------------------------------------
const twoExcelFormRef = ref<FormInst | null>(null)
const twoExcelForm = reactive({
   excelOneName: '',
   excelOneUrl: '',
   excelTwoName: '',
   excelTwoUrl: '',
})
const twoExcelRules: FormRules = {
    excelOneName: [ { required: true, message: '必须选择文件才行哦~~',trigger: ['change', 'blur'] } ],
    excelTwoName: [ { required: true, message: '必须选择文件才行哦~~',trigger: ['change', 'blur'] } ],
}
const excelOne = ref<UploadFileInfo[]>([]);
const excelTwo = ref<UploadFileInfo[]>([]);
const isUploadExcelOneDone = ref(false); // 第一个文件是否上传成功
const isUploadExcelTwoeDone = ref(false); // 第二个文件是否上传成功


// 选择文件后填充第一个文件对应状态
const handleFileOneChange = (options: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
  const saveSuffix = [ 'xlsx','xls','csv' ];
  const saveSuffixSet = ref(new Set(saveSuffix)); 
  const lastDotIndex = options.fileList[0].name.lastIndexOf('.');
  const fileSuffix =  (lastDotIndex > 0) ? options.fileList[0].name.substring(lastDotIndex + 1) : '';
  if (!saveSuffixSet.value.has(fileSuffix)) {
    message.error("仅允许上传Excel文件/CSV文件!");
    excelOne.value = [];
    return;
  }
  excelOne.value = options.fileList;
  // 选择文件之后将 图标调大  文字隐藏
  textIsShowOne.value = false;
  tabOneIconSizeOne.value = 65; // 调整图标大小

};
// 删除已选择的第一个文件
const handleRemoveExcelOne = async (options: { file: UploadFileInfo }) => {
    textIsShowOne.value = true;
    tabOneIconSizeOne.value = 30;
    try {
        isUploadExcelOneDone.value = false; // 文件是否上传成功
        excelOne.value = [];
        message.info('文件已删除');
    } catch (error) {
        message.error(`删除失败: ${(error as Error).message}`);
    }
    flushForm.value = false;
    flushForm.value = true;
};


// 选择文件后填充第二个文件对应状态
const handleFileTwoChange = (options: { file: UploadFileInfo, fileList: UploadFileInfo[] }) => {
  const saveSuffix = [ 'xlsx','xls','csv' ];
  const saveSuffixSet = ref(new Set(saveSuffix)); 
  const lastDotIndex = options.fileList[0].name.lastIndexOf('.');
  const fileSuffix =  (lastDotIndex > 0) ? options.fileList[0].name.substring(lastDotIndex + 1) : '';
  if (!saveSuffixSet.value.has(fileSuffix)) {
    message.error("仅允许上传Excel文件/CSV文件!");
    excelOne.value = [];
    return;
  }
  excelTwo.value = options.fileList;
  textIsShowTwo.value = false;
  tabOneIconSizeTwo.value = 65;
};
// 删除已选择的第二个文件
const handleRemoveExcelTwo = async (options: { file: UploadFileInfo }) => {
    try {
        isUploadExcelTwoeDone.value = false; // 文件是否上传成功
        excelTwo.value = [];
        message.info('文件已删除');
        textIsShowTwo.value = true;
        tabOneIconSizeTwo.value = 30;
    } catch (error) {
        message.error(`删除失败: ${(error as Error).message}`);
    }
};



const excelMinioUrl = ref('')
// 开始对比
const chkExcelAllCellDiff = async (e: MouseEvent) => {
  e.preventDefault()
  excelMinioUrl.value = ''
  // 检查文件是否存在
  if (!excelOne.value[0]?.file || !excelTwo.value[0]?.file) {
    message.error("请先选择文件！")
    return
  }

  // 校验文件后缀
  const saveSuffix = ['xlsx','xls','zip'];
  const saveSuffixSet = ref(new Set(saveSuffix)); 

  const excelOneLastDotIndex = excelOne.value[0].file.name.lastIndexOf('.'); 
  const excelTwoLastDotIndex = excelTwo.value[0].file.name.lastIndexOf('.'); 

  const excelOneFileSuffix =  (excelOneLastDotIndex > 0) ? excelOne.value[0].file.name.substring(excelOneLastDotIndex + 1) : '';
  const excelTwoFileSuffix =  (excelTwoLastDotIndex > 0) ? excelTwo.value[0].file.name.substring(excelTwoLastDotIndex + 1) : '';
  if (!saveSuffixSet.value.has(excelOneFileSuffix) || !saveSuffixSet.value.has(excelTwoFileSuffix)) {
    message.error("请上传安全Excel文件!");
    excelOne.value = [];
    excelTwo.value = [];
    return;
  }

  // 传递给后端的参数绑定
  let formData = {...twoExcelForm}

  try {
    isButtonShow.value = true

  // 添加await并捕获异常
  const res = await request.uploadExcel<{ url: string }>(
      "/dragon/chkExcelAllCell",
      [excelOne.value[0].file, excelTwo.value[0].file], // 传递两个文件
      formData,
      {
        headers: { 'X-Upload-Type': 'ExcelFile' },
        timeout: 600000,
      },
      { 
        fieldName: 'file', // 统一字段名  和后端 @RequestParam 名称保持一致
        multipleField: true // 启用多字段模式
       } 
    );

    if (res.code === 200) {
      const excelMinioUrlStr = (res.data+"").split('?')[0]; 
      excelMinioUrl.value = excelMinioUrlStr; // 保存文件下载链接
      message.success("文件对比成功,请点击按钮下载结果文件!");
    }
  } catch (error) {
    // @ts-ignore
    if (axios.isAxiosError(error)) {
      // @ts-ignore
       if (error.code === 'ECONNABORTED') {
        message.error("上传超时，请检查网络后重试");
        // @ts-ignore
      } else if (error.response?.status === 500) {
        message.error("服务器处理文件超时，请尝试压缩图片");
      }
    }
  } finally {
    isButtonShow.value = false
  }

}

// 两种方式打开链接
const openExternalUrl = () => {
  // window.location.href = excelMinioUrl.value;
  window.open(excelMinioUrl.value, "_blank");
};

onMounted(() => {
  // @ts-ignore
  userdata.across_num = userInfo._object.userInfo.across_num
  // @ts-ignore
  userdata.avatarBase64 = userInfo._object.userInfo.avatarBase64
  // @ts-ignore
  userdata.avatar_url = userInfo._object.userInfo.avatar_url
  // @ts-ignore
  userdata.create_tm = userInfo._object.userInfo.create_tm
  // @ts-ignore
  userdata.email = userInfo._object.userInfo.email
  // @ts-ignore
  userdata.encrypt_pwd = userInfo._object.userInfo.encrypt_pwd
  // @ts-ignore
  userdata.encryption_algorithm = userInfo._object.userInfo.encryption_algorithm
  // @ts-ignore
  userdata.freeze_ornnt = userInfo._object.userInfo.freeze_ornnt
  // @ts-ignore
  userdata.id = userInfo._object.userInfo.id
  // @ts-ignore
  userdata.role_num = userInfo._object.userInfo.role_num
  // @ts-ignore
  userdata.tel_num = userInfo._object.userInfo.tel_num
  // @ts-ignore
  userdata.update_tm = userInfo._object.userInfo.update_tm
  // @ts-ignore
  userdata.username = userInfo._object.userInfo.username
  // @ts-ignore
  userdata.wechat_abt = userInfo._object.userInfo.wechat_abt
})

// 上传Excel进行处理 --------------------------------------------------
  
</script>
  


































  <style lang="scss" scoped>
  // ----------------------------------------------------------------------
  // 调整抽屉里面 图片显示的大小 无论上有没有选择图片都显示相同的大小
  :deep(.n-upload) {
    // 上传触发区（未选择文件时的拖拽区域）
    .n-upload-trigger.n-upload-trigger--image-card {
      width: 120px !important;
      height: 100px !important;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
    }
  
    // 已上传文件的显示区域（选择文件后的图片容器）
    .n-upload-file-list {
      .n-upload-file {
        width: 100% !important;  // 强制宽度
        height: 50px !important; // 强制高度
  
        // 覆盖 naive-ui 的默认图片样式
        .n-image {
          width: 100% !important;
          height: 100% !important;
          object-fit: cover !important; // 保持图片填充
        }
      }
    }
  }
  // ----------------------------------------------------------------------
  
  
  
  
  
  
.mobile-content {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 8px;

  :deep(.n-infinite-scroll) {
    flex: 1;
    height: 100% !important;
  }
}

/* 调整PC端轮播图高度 */
.n-carousel {
  height: 80vh;
  max-height: 800px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .mobile-card {
    height: 55vh;
    min-height: 250px;
  }
  
  .mobile-content {
    padding: 0;
    overflow-x: auto;
  }
}
.mobile-card {
  height: 60vh; /* 卡片占可视高度的60% */
  min-height: 300px;
  margin-bottom: 12px;
  
  :deep(.n-card__content) {
    height: 100%;
    padding: 0;
  }
}

.mobile-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}
.grid-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  // overflow: hidden;

  :deep(.n-grid) {
    height: 100%;
  }
}

.main-content {
  height: 100vh;
  display: flex;
  flex-direction: column;

  :deep(.n-card__content) {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
}

.full-height-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.content-wrapper {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
  padding: 20px;
}

.sidebar {
  height: 100%;
  overflow-y: auto;
}

.scroll-wrapper {
  min-height: 100%;
  padding-bottom: 20px;
}



/* 响应式断点处理 */
@media (max-width: 768px) {
  .full-height-tabs {
    :deep(.n-tabs-nav) {
      overflow-x: auto;
      width: calc(100% + 16px);  /* 解决滚动条遮挡问题 */
      margin-left: -8px;
      padding-left: 8px;
      
      :deep(.n-tab) {
        white-space: nowrap;
        padding: 0 12px;
        min-width: 80px;
      }
    }
  }
}

:deep(.n-tabs-nav::-webkit-scrollbar) {
  height: 6px;
  background-color: #f5f5f5;
}

:deep(.n-tabs-nav::-webkit-scrollbar-thumb) {
  background-color: #aaa;
  border-radius: 3px;
}

// 隐藏所有tab-pane的默认滚动条
:deep(.n-tabs-pane) {
  &::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
    background: transparent;
  }
  
  -ms-overflow-style: none;  // IE/Edge
  scrollbar-width: none;    // Firefox
}

// 定义隐藏滚动条的混合宏
%hide-scrollbar {
  &::-webkit-scrollbar {
    display: none;
  }
}

// =========滚动条样式
// 全局自定义滚动条（仅作用于允许滚动的区域）
:deep(.custom-scroll) {
  $thumb-color: rgba(144, 147, 153, 0.5);
  $track-color: rgba(255, 255, 255, 0.1);
  
  // 滚动条轨道
  &::-webkit-scrollbar-track {
    background: var(--n-color); 
    border-radius: 4px;
  }

  // 滚动条滑块
  &::-webkit-scrollbar-thumb {
    background: $thumb-color;
    border-radius: 8px;
    border: 2px solid transparent;
    background-clip: content-box;
    
    &:hover {
      background: rgba(144, 147, 153, 0.8);
    }
  }

  // 横向滚动条
  &::-webkit-scrollbar:horizontal {
    height: 10px;
  }

  // 纵向滚动条
  &::-webkit-scrollbar:vertical {
    width: 10px;
  }

  // 暗色模式适配
  @media (prefers-color-scheme: dark) {
    $thumb-color: rgba(101, 104, 109, 0.6);
    $track-color: rgba(0, 0, 0, 0.3);
    
    &::-webkit-scrollbar-track {
      background: $track-color;
    }
    
    &::-webkit-scrollbar-thumb {
      background: $thumb-color;
    }
  }
}




.upload-loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.485);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(2px);
}

/* 高度计算优化 */
.content-container {
  height: calc(100vh - 120px); /* 根据实际header高度调整 */
  overflow-y: auto;
}




.custom-file-preview {
  width: 100%;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.file-type-icon {
  text-align: center;
  .file-extension {
    display: block;
    margin-top: 8px;
    font-weight: bold;
    color: rgba(0,0,0,.85);
  }
}



.download-tips {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 12px 24px;
  background: rgba(128, 55, 230, 0.917);
  color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  animation: slideIn 0.5s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
  